package com.pn.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/*
  gateway的配置类:
 */
@Configuration
public class GatewayConfig {

    //注入redis模板
    @Autowired
    private StringRedisTemplate redisTemplate;

    //给认证授权中心auth-service服务配置路由
    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder routeLocatorBuilder){
        //拿到路由构建器
        RouteLocatorBuilder.Builder builder = routeLocatorBuilder.routes();
        //构建路由
        return builder.route("auth-service-router", t ->
                t.path("/oauth/token")
                        .filters(f -> f.modifyResponseBody(String.class, String.class, ((exchange, jsonStr) -> {
                            //将auth-server向后置过滤器响应的json串转成map
                            JSONObject jsonObj = JSON.parseObject(jsonStr);
                            //拿响应的token
                            String token = jsonObj.getString("access_token");
                            //拿token的过期时间
                            Long times = jsonObj.getLong("expires_in");
                            //登录成功
                            if(StringUtils.hasText(token)){
                                //将token存储到redis
                                redisTemplate.opsForValue().set(token, "", times, TimeUnit.SECONDS);
                            }
                            //不管登录成功还是失败都将auth-service响应的json串再响应给前端
                            return Mono.just(jsonStr);
                        })))
                        .uri("lb://auth-server")
        ).build();
    }
}
